
(function($) {
/*********************************面板组件*********************************************/
$.widget("youi.panel", {
	init:function(){
		var uiPanelContent = this.element.addClass('youi-panel').wrap('<div/>'),
			uiPanelContainer = (this.uiPanelContainer = uiPanelContent.parent());
		this.createHeader();
		this.createCenter();
		this.createFooter();
		if(jQuery.isFunction(this.options.after)){
			this.options.after.apply(this);
		}
	},
	
	createHeader:function(){
		this.uiPanelContainer.prepend('<div class="youi-panel-tl"><div class="youi-panel-tr"><div class="youi-panel-tc"><div class="youi-panel-header youi-unselectable" style="-moz-user-select: none;"><span class="youi-panel-header-text"></span></div></div></div></div>');
		$('.youi-panel-header-text',this.uiPanelContainer).text(this.options.caption||'');
	},
	
	createCenter:function(){
		//var paenlContianter = this.element.parent();
		this.uiPanelContainer.append('<div class="youi-panel-bwrap"><div class="youi-panel-ml"><div class="youi-panel-mr"><div class="youi-panel-mc"><div class="youi-panel-body"></div></div></div></div>');
		this.uiPanelContainer.find('.youi-panel-body').append(this.element);
	},
	
	createFooter:function(){
		if(this.options.footer){
			this.uiPanelContainer.append('<div class="youi-panel-bl"><div class="youi-panel-br"><div class="youi-panel-bc"><div class="youi-panel-footer"></div></div></div></div>');
			this.uiPanelContainer.find('.youi-panel-footer').append(this.options.footer);
		}
	}
});

$.extend($.youi.panel,{
	defaults:{
		
	}
});

/*********************************表格组件*********************************************/
$.widget("youi.grid", {
	currentPageIndex:0,
	
	sortParam:null,
	
	/**
	 * 初始化函数
	 */
	init: function() {
		$.youi.time.start();
		var o = this.options;
		this.cols=[];//列属性对象数组
		this.checkedList = [];//记录当前选中的单元格
		this.idKeyArray = [];
		this.records = [];
		if(this.options.idKeys){this.idKeyArray = this.options.idKeys.split(',');}
		
		this.element.addClass('youi-widget-grid');
		this.initCols();//
		
		this.createFilterArea();
		this.createHeadArea();
		this.createDataArea();
		this.createNavigator();
		
		this.goPage(1);//加载第一页数据
	},
	
/*********************************私有方法************************************************/
	initCols:function(){
		var cols = this.options.cols;
		var col;//列对象
		
		if(this.options.showNum){
			this.cols.push({
				type:'num',
				caption:'<div class="num"/>',
				property:'num',
				align:'center',
				width:20
			});
		}
		
		if(this.options.showCheckbox){
			this.cols.push({
				type:'checkbox',
				caption:'<div class="checkbox"/>',
				property:'checkbox',
				align:'center',
				width:16
			});
		}
		for(var i=0;i<cols.length;i++){
			col = $.extend({},$.youi.grid.defaultCol,cols[i]);
			if($.youi.propertyPassed(col.property)===true){
				this.cols.push(col);
			}
			col = null;
		}
	},
	
	createFilterArea:function(){
		var self = this;
		var filters = this.options.filters;
		var columns = this.options.filterColumns;
		
		if(filters&&filters.length>0){
			this.filterContainer = $('<div/>');
			var filterTable = $('<table width="100%" height="100%" tablelayout="fixed" border="0" cellSpacing="0" cellPadding="0"/>');
			var rows = filters.length/columns;
			var passedCount = 0;
			
			for(var i=0;i<rows;i++){
				var tr = document.createElement('tr');
				filterTable.append(tr);
			}
			
			$.each(filters,function(i){
				var passed = $.youi.propertyPassed(this.property);
				if(passed){
					var trRow = Math.ceil((i+1-passedCount)/columns)-1;
					trRow = (trRow<0)?0:trRow;
					var field = $('<div/>');
					$('tr:eq('+trRow+')',filterTable).append($('<td/>').append(field));
					field[this.fieldType](this);
				}else{
					passedCount++;
				}
			});
			this.filterContainer.append(filterTable);
			this.element.prepend(this.filterContainer);
			
			footerContainer = $('<div align="center"/>');
			var  submitButton = $('<input class="youi-button" type="submit" value="查询"/>');
			var  resetButton =  $('<input class="youi-button" type="reset"  value="重填"/>');
			
			submitButton.bind('click',function(){
				self.loadDataClearChecked();
			});
			
			resetButton.bind('click',function(){
				self.filterContainer.find('.youi-field').each(function(){
					$(this).fieldReset();
				});
			});
			
			footerContainer.append(submitButton).append('&nbsp;').append(resetButton);
			
			this.filterContainer.panel({caption:this.options.filterCaption,footer:footerContainer});
			filterTable = null;
		}
	},
	/**
	 * 创建表头区域
	 */
	createHeadArea:function(){
		var self = this;
		this.headTableContainer =  $('<div class="youi-table-headTableContainer"/>');
		var headTable = $('<table width="100%" height="100%" tablelayout="fixed" border="0" cellSpacing="0" cellPadding="0"/>');
		var headTr = $('<tr/>');
		$.each(this.cols,function(colIndex){
			var th = $('<th align="center" class="youi-widget-grid-headCell"/>');
			th.append('<div class="head">'+this.caption+'</div>');
			if(this.sort){
				th.find('>div').append('<img class="youi-widget-grid-sort-icon" src="'+$.youi.serverConfig.path+'images/youi/s.gif"/>');
			}
			th.click(function(){
				self.doClickHeadCell(this,colIndex);
			});
			headTr.append(th);
		});
		headTable.append(headTr);
		this.headTableContainer.append(headTable);
		this.element.append(this.headTableContainer);
	},
	
	createDataArea:function(){
		var self = this;
		this.dataTableContainer =  $('<div class="youi-table-dataTableContainer"/>');
		this.element.append(this.dataTableContainer);
		
		this.dataTableContainer.scroll(function(){
			self.headTableContainer[0].scrollLeft = this.scrollLeft;
		});
	},
	/**
	 * 创建表格导航栏
	 */
	createNavigator:function(){
		this.pageIndexComposite = $('<span/>');
		this.navigatorContainer = $('<div class="youi-table-nagivator" align="right" style="padding:2px 0 2px 0;"/>');
		this.navigatorContainer.append(this.pageIndexComposite);
		this.dataTableContainer.after(this.navigatorContainer);
	},
	
	doClickHeadCell:function(domTh,colIndex){
		var col = this.cols[colIndex];
		var type = col.type;
		
		switch(type){
			case 'checkbox':
				this.doCheckAll(domTh);
				break;
			case 'num':
				break;
			default :
				var sort = col.sort;
				var sortType = 'asc';
				var sortIcon = $('img.youi-widget-grid-sort-icon',domTh);
				if(sortIcon.toggleClass('desc').is('.desc')){
					sortType = 'desc';
				}else{
					sortIcon.removeClass('desc').addClass('asc');
				}
				if(sort=='database'){
					this.sortParam="&sort:"+sortType+'='+col.property;
					this.loadDataClearChecked();
				}else if(sort=='page'){
					this.sortTable(sortType,col.dataType,colIndex);
				}
		}
		col = null;
	},
	
	doCheckAll:function(domTh){
		var checkAll = $('.checkbox',domTh);
		if(checkAll.length!==0){
			checkAll.toggleClass('checked');
			if(checkAll.is('.checked')){
				this.doCheckedList(this.dataTableContainer.find('.checkbox').not('.checked'),true);
			}else{
				this.doCheckedList(this.dataTableContainer.find('.checked'),false);
			}
		}
		checkAll = null;
	},
	
	loadData:function(){
		var totalCount;
		$('.checked',this.headTableContainer).removeClass('checked');
		var self = this;
		var params = this.getParams();
		$.youi.log.info('params:'+params);
		if(this.options.src){
			$.ajax({
				type: this.options.ajaxType,
				url:  this.options.src,
				dataType:this.options.srcType,
				data: params,
				success: function(result){
					var datas = $.youi.parseDatas(result,self.options.srcType);
					self.initDataTable(datas.records,datas.totalCount);
				}
			});
		}else{
			if(this.options.mock){
				totalCount = 200;
				this.initDataTable($.youi.mockRecords({properties:this.options.cols,size:this.options.pageSize,beginIndex:(parseInt(this.currentPageIndex-1)*this.options.pageSize)}),totalCount);
			}
		}
	},
	
	loadDataClearChecked:function(){
		this.records = [];//清空结果集
		this.checkedList = [];
		this.loadData();
	},
	
	getParams:function(){
		var pageSize = this.options.pageSize;
		var pageIndex = this.currentPageIndex;
		var params = [];
		params.push($.youi.connectKeyValue('pager:pageSize',pageSize));
		params.push($.youi.connectKeyValue('pager:pageIndex',pageIndex));
		if(this.filterContainer){
			this.filterContainer.find('.youi-field').each(function(){
				params.push($.youi.connectKeyValue('property:'+$(this).attr('ref-property'),$(this).fieldValue()));
			});
		}
		if(this.sortParam){
			params.push(this.sortParam);
			this.sortParam = null;
		}
		return params.join('').substring(1);
	},
	
	initDataTable:function(records,totalCount){
		var tableArray = [];
		tableArray.push('<table tablelayout="fixed" border="0" cellSpacing="0" cellPadding="0">');
		var trClassName;
		var beginIndex = (this.currentPageIndex-1)*this.options.pageSize;
		for(var i=0;i<Math.min(records.length,this.options.pageSize);i++){
			var rowIndex = beginIndex+i+1;
			if(i%2===0){
				trClassName = 'old';
			}else{
				trClassName = 'even';
			}
			
			var record = records[i];
			var idKeyValueArray = [];
			var idKeyValues;
			$.each(this.idKeyArray,function(){
				idKeyValueArray.push(record[this]);
			});
			if(idKeyValueArray.length===0){idKeyValueArray.push(rowIndex);}//使用行号作为关键值
			
			idKeyValues = idKeyValueArray.join();
			this.records[idKeyValues] = record;
			//var idKeys = record[]
			tableArray.push('<tr idKeyValues="'+idKeyValues+'" class="');
			tableArray.push(trClassName);
			tableArray.push('" onclick="$.youi.grid.clickRow(this,event)" onmouseover="$.youi.grid.mouseoverRow(this,event)" onmouseout="$.youi.grid.mouseoutRow(this,event)">');
			for(var j=0;j<this.cols.length;j++){
				var col = this.cols[j];
				var value = record[col.property];
				
				tableArray.push('<td value="'+(value||'')+'" align="'+col.align+'" onclick="$.youi.grid.clickCell(this,\''+col.type+'\',event)" onmouseover="$.youi.grid.mouseoverCell(this,event)" onmouseout="$.youi.grid.mouseoutCell(this,event)">');
				tableArray.push($.youi.grid.makeDataTdContentStr(value,record,col,rowIndex,this.checkedList[idKeyValues]));
				tableArray.push('</td>');
			}
			tableArray.push('</tr>');
		}
		tableArray.push('</table>');
		
		this.dataTableContainer.empty().append(tableArray.join(''));
		this.showNavigator(totalCount);
		
		$.youi.time.start();
		this.positionGrid();
		$.youi.time.end('表格['+this.element.attr('id')+']计算位置');
		
		$.youi.time.end('表格['+this.element.attr('id')+']加载总');
	},
	
	positionGrid:function(){
		var dataTable = this.dataTableContainer.find('>table'),
			headTable = this.headTableContainer.find('table'),
			dataTableContainerCss={},
			headTableContainerCss={},
			contaierWidth=0,
			tableWidth = 0,
			tableHeight = 0;
		//计算容器宽度
		if($.browser.msie){
			contaierWidth = this.element.width()-1;
		}else{
			contaierWidth = this.element.width()-2;
		}
		
		var firstDataTr = dataTable.find('tr:first');
		
		//重新计算表格宽度
		$.each(this.cols,function(i){
			var td = firstDataTr.find('td:eq('+i+')');
			$.youi.log.info(this.width+'...'+td.width());
			if(this.width<td.width()){
				this.width = td.width();
			}
			tableWidth+=this.width;
		});
		//判断是否出现滚动条
		var hasHScroll = this.hasHScroll(tableWidth,contaierWidth),
			hasVScroll = this.hasVScroll(dataTable);
			
		tableHeight = dataTable.outerHeight();
		
		dataTableContainerCss.width  = contaierWidth;
		dataTableContainerCss.height = tableHeight;
		headTableContainerCss.width = contaierWidth;
		
		if(hasHScroll){//横向滚动条
			dataTableContainerCss.overflowX='auto';
			dataTableContainerCss.height+=18;
		}else{
			tableWidth = contaierWidth;
			if(hasVScroll){
				tableWidth-=18;
			}
		}
		
		if(hasVScroll){//纵向滚动条
			dataTableContainerCss.height=this.options.scrollHeight;
			dataTableContainerCss.overflowY='auto';
			headTableContainerCss.overflowY='scroll';
			
			this.getCoverScroll().css({
				right:0,
				top:this.headTableContainer.position().top
			});
			
			if(!$.browser.msie){
				headTableContainerCss.width-=18;
			}
		}
		
		this.dataTableContainer.css(dataTableContainerCss);
		this.headTableContainer.css(headTableContainerCss);
		
		$.each(this.cols,function(i){
			var pWidth = parseInt((this.width/tableWidth)*100)+'%';
			firstDataTr.find('td:eq('+i+')').width(pWidth);
			headTable.find('th:eq('+i+')').width(pWidth);
		});
		dataTable.width(tableWidth);
		headTable.width(tableWidth);
	},
	
	getCoverScroll:function(){
		var coverScroll = this.element.find('.youi-widget-grid-coverScroll');
		if(coverScroll.length==0){
			coverScroll = $('<div class="youi-widget-grid-coverScroll"/>');
			this.element.append(coverScroll);
		}
		return coverScroll;
	},
	//
	hasVScroll:function(dataTable){
		return this.options.scrollHeight&&this.options.scrollHeight<dataTable.outerHeight();
	},
	//表格宽于容器
	hasHScroll:function(tableWidth,contaierWidth){
		return tableWidth>contaierWidth;
	},
	
	/**
	 * 显示分页导航条
	 */
	showNavigator:function(totalCount){
		var pageIndex = this.currentPageIndex;
		var pageSize  = this.options.pageSize;
		var pageCount = Math.ceil(totalCount/pageSize);
		if(pageIndex>pageCount){//如果当前定位大于最大页数，置当前定位为最大页数
			this.goPage(pageCount);
		}
		this.pageIndexComposite.empty().append('<span>\u5171\u3010'+totalCount+'\u3011\u6761\u8bb0\u5f55</span>');
		this.createGoPageSpan(pageIndex-1,pageCount,$.youi.grid.resource.prev);
		
		var pIndex = Math.min(2,pageCount);
		for(var i=1;i<=pIndex;i++){
			this.createGoPageSpan(i,pageCount);
		}
		
		if(pageIndex>5&&pageIndex<=pageCount-5){
			this.pageIndexComposite.append('...');
			for(var i=1;i>-2;i--){
				this.createGoPageSpan(pageIndex-i,pageCount);
			}
		}else{
			if(pageIndex>2&&pageIndex<=pageCount-5){
				for(var i=2;i<pageIndex;i++){
					this.createGoPageSpan(i+1,pageCount);
				}
			}
		}
		
		if(pageCount>5){
			this.pageIndexComposite.append('...');
			if(pageIndex>pageCount-5&&pageIndex<pageCount-1){
				for(var i=pageIndex;i<pageCount-1;i++){
					this.createGoPageSpan(i,pageCount);
				}
			}
			for(var i=1;i>=0;i--){
				this.createGoPageSpan(pageCount-i,pageCount);
			}
		}else{
			for(var i=3;i<=pageCount;i++){
				this.createGoPageSpan(i,pageCount);
			}
		}
		this.createGoPageSpan(pageIndex+1,pageCount,$.youi.grid.resource.next);
		
		if(this.options.showNagivator==false||pageCount==1){
			$('.youi-table-nagivator',this.element).hide();
		}else{
			$('.youi-table-nagivator',this.element).show();
		}
	},
	/**
	 * 创建导航定位
	 */
	createGoPageSpan:function(pageIndex,pageCount,text){
		var p = this;
		if(!text)text=pageIndex;
		var pageIndexSpan = $('<a href="#" class="youi-widget-grid-pageIndexSpan">'+text+'</a>');
		if(this.currentPageIndex==pageIndex){
			pageIndexSpan.css('borderColor','#000');
		}
		pageIndexSpan.mouseover(function(){
			$(this).addClass('youi-widget-grid-pageIndexSpan-over');
		}).mouseout(function(){
			$(this).removeClass('youi-widget-grid-pageIndexSpan-over');
		}).click(function(){
			if(p.$EditTd&&!window.confirm($.youi.grid.resource.abandonEdit)){
				p.hiddenWidget();//隐藏编辑单元
				return false;
			}
			
			if(pageIndex>=1&&pageIndex<=pageCount)
				p.goPage(pageIndex);
			return false;
		}).dblclick(function(){
			return false;
		});
		
		this.pageIndexComposite.append(pageIndexSpan);
		pageIndexSpan = null;
	},
	
	doCheckRow:function(domTr,isCtrl,isShift){
		var checkHandler = $('.checkbox',domTr);
		var idKeyValues = domTr.getAttribute('idKeyValues');
		var checked = checkHandler.toggleClass('checked').is('.checked');
		this.checkedList[idKeyValues]=checked;
		if(isCtrl==true){
			
		}else if(isShift==true){
			
		}else{
			this.doCheckedList($('td>.checked',this.dataTableContainer).not(checkHandler),false);
		}
	},
	
	doCheckedList:function(elements,checked){
		var self = this;
		if(checked==true){
			elements.addClass('checked').each(function(){
				var idKeyValues = this.parentNode.parentNode.getAttribute('idKeyValues');
				self.checkedList[idKeyValues]=true;
			});
		}else{
			elements.removeClass('checked').each(function(){
				var idKeyValues = this.parentNode.parentNode.getAttribute('idKeyValues');
				self.checkedList[idKeyValues]=false;
			});
		}
	},
	
	/**
	 * 对界面上的列进行排序A-Z Z-A
	 */
	sortTable:function(sortType,dataType,column){
		var newDir = sortType == "asc" ? 1 :-1;
		var self = this;
		if (dataType == 'float') {
			findSortKey = function($cell) {
				var key = parseFloat($cell.html().replace(/,/g, ''));
				return isNaN(key) ? 0 : key;
			}
		} else if (dataType=='int') {
			findSortKey = function($cell) {
				return IntNum($cell.html().replace(/,/g, ''))
			}
		} else if(dataType == 'date') {
			findSortKey = function($cell) {
				var fd = ts.p.colModel[column].datefmt || "Y-m-d";
				return parseDate(fd,$cell.html()).getTime();
			}
		} else {
			findSortKey = function($cell) {
				return $cell.text().toUpperCase();
			}
		}
		
		var rows = this.dataTableContainer.find('tbody > tr').get();
		if(rows.length==1)return;//1行不排序
		$.each(rows, function(index, row) {
			row.sortKey = findSortKey($(row).children('td').eq(column));
			var a =1;
		});
		
		rows.sort(function(a, b) {
			if (a.sortKey < b.sortKey) return -newDir;
			if (a.sortKey > b.sortKey) return newDir;
			return 0;
		});
		
		$.each(rows, function(index, row) {
			if(index%2==1){
				row.className = 'even';
			}else{
				row.className = 'old';
			}
			
			$('tbody',self.dataTableContainer).append(row);
			row.sortKey = null;
		});
	},
	/**************************公用方法*******************************************************/
	/**
	 * 根据参数pageIndex跳转到对应的页面
	 */
	goPage:function(pageIndex){
		if(this.currentPageIndex!=pageIndex){
			this.currentPageIndex = pageIndex;
			this.loadData();
		}
	}
});


$.extend($.youi.grid,{
	resource:{
		submit				:'\u67e5\u8be2',//查询
		prev				:'\u4e0a\u4e00\u9875',//上一页
		next				:'\u4e0b\u4e00\u9875',//下一页
		reset				:'\u6e05\u7a7a',//清空
		notFoundRecord		:'\u6ca1\u6709\u627e\u5230\u8bb0\u5f55\uff01',//未找到记录！
		abandonEdit			:'\u653e\u5f03\u7f16\u8f91\u6570\u636e?',//放弃编辑数据？
		
		addRecord			:'\u589e\u52a0\u8bb0\u5f55',//增加记录
		removeRecord		:'\u5220\u9664\u8bb0\u5f55',//删除记录
		print				:'\u6253\u5370',//打印
		exportXML			:'\u5bfc\u51faXML',//导出XML
		exportEXCEL			:'\u5bfc\u51faEXCEL'//导出EXCEL
	},
	defaults: {
		pageSize:10,
		filterColumns:2,
		ajaxType:"POST"
	},
	
	defaultCol:{
		caption		:'',
		params		:'',
		target		:'_blank',
		type		:'common',
		width		:100,
		align		:'center',
		dataType	:$.youi.dataType.string
	},
	
	makeDataTdContentStr:function(value,record,col,index,checked){
		var tdInnerHtml = value;
		var type = col.type;
		var checkedStyle = (checked==true)?'checked':'';
		//alert(checkedStyle);
		switch(type){
			case 'num':
				tdInnerHtml = '<div class="num">'+index+'</div>';
				break;
			case 'checkbox':
				tdInnerHtml = '<div class="checkbox '+checkedStyle+'"/>';
				break;
			case 'common':
				if(col.convert){
					try{
						tdInnerHtml = $.youi.serverConfig.convertArray[col.convert][value];
					}catch(err){
						$.youi.log.info('convert['+col.convert+'] not exsit!');
					}
				}
				break;
			case 'link':
				var params = col.params;
				var param;
				var paramValue;
				if(params){
					var paramArray = params.split(',');
				}
				var hrefArray = [];
				hrefArray.push(col.href);
				if(col.href.indexOf('?')=='-1'){
					hrefArray.push('?1=1');
				}
				for(var i=0;i<paramArray.length;i++){
					param 		= paramArray[i];
					paramValue 	= record[param];
					if(paramValue){
						hrefArray.push('&');
						hrefArray.push(param);
						hrefArray.push('=');
						hrefArray.push(paramValue);
						param = null;
						paramValue = null;
					}
				}
				
				tdInnerHtml = '<a target="'+col.target+'" href="'+hrefArray.join('')+'">'+value+'</a>';
				break;
			default:
				
				break;
		}
		return tdInnerHtml||'&nbsp;';
	},
	
	clickRow:function(domTr,event){
		var instance = $.youi.grid.getInstanceByDomChild(domTr);
		var idKeyValues = domTr.getAttribute('idKeyValues');
		//alert(event);
		var isCtrl = event.ctrlKey;
		var isShift = event.shiftKey;
		if(instance){
			if(instance.options.showCheckbox===true){
				instance.doCheckRow(domTr,isCtrl,isShift);
			}
			if($.isFunction(instance.options.rowClick)){
				instance.options.rowClick(domTr,new $.youi.record(instance.records[idKeyValues]),$('.checkbox',domTr).is('checked'));
			}
		}
	},
	
	mouseoverRow:function(domTr,event){
		$(domTr).addClass('over');
	},
	
	mouseoutRow:function(domTr,event){
		$(domTr).removeClass('over');
	},
	
	clickCell:function(domTd,type,event){
		//var instance = $.youi.grid.getInstanceByDomChild(domTr);
		//instance.showWidget(type,domTd);
		
	},
	
	mouseoverCell:function(domTd){
		
	},
	
	mouseoutCell:function(domTd){
		
	},
	
	getInstanceByDomChild:function(domElement){
		var instance = null;
		var elements = $(domElement).parents();
		
		$.each(elements,function(){
			if($(this).is('.youi-widget-grid')){
				instance = $.data(this, 'grid');
			}
		});
		return instance;
	}
});

})(jQuery);